package com.shb.jutils.commons;

import javax.servlet.http.HttpServletRequest;
/**
 * 获取路径工具类
 * @author shb
 *
 */
public class PathUtil {
	/**
	 * 1.web项目获取Tomcat下bin目录
	 * 2.java项目获取工作空间的项目目录
	 * @return
	 */
	public static String getBinPath(){
		return System.getProperty("user.dir");
	}
	
	/**
	 * 获取类的路径
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static String getClassPath(Class clazz){
		String path = clazz.getResource("").toString();
		return path.substring(path.indexOf("/") + 1);
	}
	
	/**
	 * 获取编译后的classes目录绝对路径
	 * @return
	 */
	public static String getAbsoluteWebContentPath(){
		return Thread.currentThread().getContextClassLoader().getResource("").getPath().substring(1);
	}
	
	/**
	 * 用servlet获取项目目录绝对路径
	 * @param request
	 * @return
	 */
	public static String getAbsoluteProPath(HttpServletRequest request){
		return request.getSession().getServletContext().getRealPath("");
	}
	
	/**
	 * 用servlet获取浏览器地址
	 * @param request
	 * @return
	 */
	public static String getRequestURL(HttpServletRequest request){
		return request.getRequestURL().toString();
	}
	
	/**
	 * 用servlet获取浏览器地址指向的绝对路径
	 * @param request
	 * @return
	 */
	public static String getAbsoluteURL(HttpServletRequest request){
		return request.getSession().getServletContext().getRealPath(request.getRequestURL().toString());
	}
	
	public static void print(HttpServletRequest request){
		System.out.println("bin路径：" + PathUtil.getBinPath());
		System.out.println("PathUtil类的路径：" + PathUtil.getClassPath(PathUtil.class));
		System.out.println("classes的绝对路径：" + PathUtil.getAbsoluteWebContentPath());
		if(request != null){
			System.out.println("servlet获取项目绝对路径：" + PathUtil.getAbsoluteProPath(request));
			System.out.println("servlet获取浏览器地址：" + PathUtil.getRequestURL(request));
			System.out.println("浏览器地址指向的绝对路径:" + PathUtil.getRequestURL(request));
		}
	}
	
	public static void main(String[] args){
		PathUtil.print(null);
	}

}
